package com.mark.springsecurity.service.impl;

import com.mark.springsecurity.domain.SysRole;
import com.mark.springsecurity.dto.req.SysRoleCmd;
import com.mark.springsecurity.exception.SysRoleNameExistedException;
import com.mark.springsecurity.exception.SysRoleNotFountException;
import com.mark.springsecurity.repository.SysRoleRepository;
import com.mark.springsecurity.service.RoleService;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Optional;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {
    private final SysRoleRepository sysRoleRepository;

    public RoleServiceImpl(SysRoleRepository sysRoleRepository) {
        this.sysRoleRepository = sysRoleRepository;
    }

    @Override
    public void save(SysRole sysRole) {
        Optional<SysRole> roleName = sysRoleRepository.findByName(sysRole.getName());
        if (roleName.isPresent()) throw new SysRoleNameExistedException("角色名已存在");
        else sysRoleRepository.save(sysRole);
    }

    @Override
    public SysRole getOne(Long id) {
        Optional<SysRole> sysRole = sysRoleRepository.findByIdAndEnabled(id, Boolean.TRUE);
        if (sysRole.isPresent()) return sysRole.get();
        else throw new SysRoleNotFountException("角色不存在");
    }

    @Override
    public void update(Long id, SysRoleCmd sysRoleCmd) {
        getOne(id).update(sysRoleCmd);
    }

    @Override
    public void delete(Long id) {
        getOne(id).remove();
    }

    @Override
    public Page<SysRole> findAll(Example<SysRole> example, Pageable pageable) {
        return sysRoleRepository.findAll(example, pageable);
    }
}
